package com.EAsystem.service.Impl;

import com.EAsystem.entity.User;
import com.EAsystem.mapper.UserMapper;
import com.EAsystem.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public PageInfo<User> findAllByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.findAllWithPage();
        return new PageInfo<>(users);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }



    @Override
    public PageInfo<User> findByCondition(User user, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.findByCondition(user);
        return new PageInfo<>(users);
    }

    @Override
    @Transactional
    public boolean add(User user) {
        // 设置创建时间和更新时间
        String currentTime = sdf.format(new Date());
        user.setCreateTime(currentTime);
        user.setUpdateTime(currentTime);
        
        return userMapper.insert(user) > 0;
    }

    @Override
    @Transactional
    public boolean update(User user) {
        // 设置更新时间
        user.setUpdateTime(sdf.format(new Date()));
        
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public User login(String username, String password,Integer role) {
        return userMapper.findByUsernameAndPassword(username, password,role);
    }


}